﻿//-----------------------------------------------------------------------
// <copyright file="App.xaml.cs" author="Artak Mkrtchyan">
//     Creative Commons - GNU General Public License (http://creativecommons.org/licenses/GPL/2.0/
// </copyright>
// <author>Artak Mkrtchyan</author>
// <email>mkArtak@gmail.com</email>
// <date>15/07/2012</date>
//-----------------------------------------------------------------------

using ConsoleHoster.Common.Utilities;
using ConsoleHoster.View;
using System;
using System.IO;
using System.Windows;

namespace ConsoleHoster
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private readonly ILogger logger;

        public App()
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            try
            {
                string logFilename = String.Format("Log_{0}.log", DateTime.UtcNow.ToString("yyyy-MM-dd_hh-mm"));
                string directory = Path.Combine(Directory.GetCurrentDirectory(), "Log");
                string logPath = Path.Combine(directory, logFilename);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                this.logger = new SimpleFileLogger(logPath);
            }
            catch (Exception)
            {
                this.logger = EmptyLogger.Instance;
            }

            this.logger.LogMessage("Starting ConsoleHoster...");
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            this.logger.LogMessage("Loading main window...");
            SplashWindow.StartSplash("Initializing...");
            MainWindow tmpWindow = new MainWindow(this.logger);

            this.logger.LogMessage("Preparing to show the main window...");
            tmpWindow.Show();
            this.logger.LogMessage("Main window is shown !");
        }

        protected override void OnExit(ExitEventArgs e)
        {
            this.logger.LogMessage("Exiting application with ExitCode: '{0}'...", e.ApplicationExitCode.ToString());

            base.OnExit(e);
            this.logger.Dispose();
        }

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            this.logger.LogError("Unhandled exception has occured. Details: {0}", (e.ExceptionObject as Exception).ToString());
            MessageBox.Show("An unhandled exception occured, which was logged, in the log file! If possible, please share the log file with us on our website, and we'll try to fix it asap.  The application will terminate now.", "We're sorry - things went wrong!");

            this.Shutdown();
        }
    }
}